//
// Created by jinxin on 2021-06-10.
//
#include "server.h"
#include <stdio.h>
#include <string.h>
#include <errno.h>
#include <unistd.h>
#include <sys/epoll.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <sys/socket.h>
#include <string>
#include <fcntl.h>
#include <sys/stat.h>
#include <sys/types.h>

#define MAX_EVENTS 10000

server::server(unsigned short port)
    : m_sock(-1), m_epoll_fd(-1)
{
    m_port = port;
}

bool server::init()
{
    //创建socket描述符，并进行监听
    if ((m_sock = create_socket(m_port)) <= 0)
    {
        return false;
    }

    //设置socket为非阻塞
    set_socket_non_blocking(m_sock);

    //获取http管理单件类对象
    m_p_http_manage = http_manage::get();

    return true;
}

bool server::uninit()
{
    close(m_sock);
    return true;
}

int server::get_socket()
{
    return m_sock;
}

bool server::init_epoll()
{
    m_epoll_fd = create_epoll();
    if (m_epoll_fd == -1)
    {
        perror("create_epoll:");
        return false;
    }

    m_ev.data.fd = m_sock;
    m_ev.events = EPOLLIN | EPOLLET;

    if (epoll_ctl(m_epoll_fd, EPOLL_CTL_ADD, m_sock, &m_ev) < 0)
    {
        perror("epoll_ctl:");
        return false;
    }

    return true;
}

void server::proc_epoll(int timeout)
{
    struct epoll_event event[MAX_EVENTS];
    int iEventNum = epoll_wait(m_epoll_fd, event, MAX_EVENTS, timeout);
    for (int i = 0; i < iEventNum; i++)
    {
        if (event[i].data.fd == m_sock &&
            event[i].events & EPOLLIN)
        {
            //新连接接入
            int new_sock = -1;
            struct sockaddr_in client;
            socklen_t len = sizeof(client);
            new_sock = accept(m_sock, (struct sockaddr *)&client, &len);
            if (new_sock < 0)
            {
                // perror("accept");
                // printf("%s : %d \n", strerror(errno), new_sock);
                continue;
            }

            //创建连接对象
            m_p_http_manage->create_connection(new_sock);

            // 设置非阻塞
            set_socket_non_blocking(new_sock);

            m_ev.data.fd = new_sock;
            m_ev.events = EPOLLIN | EPOLLET;
            if (epoll_ctl(m_epoll_fd, EPOLL_CTL_ADD, new_sock, &m_ev) < 0)
            {
                perror("epoll_ctl");
                return;
            }
        }
        else
        {
            if (event[i].events & EPOLLIN)
            {
                //可读事件
                int fd = event[i].data.fd;
                //获取conn对象
                http_connection *p_conn = m_p_http_manage->get_connection(fd);
                if (p_conn == NULL)
                {
                    printf("http_connection is NULL %s %d\n",
                           __FILE__, __LINE__);
                    continue;
                }

                //接收数据
                p_conn->analyse_http_protocol(fd);
                //接收数据完成后，设置可写状态
                event[i].events = EPOLLOUT;
            }

            if (event[i].events & EPOLLOUT)
            {
                //可写事件
                int fd = event[i].data.fd;
                //获取conn对象
                http_connection *p_conn = m_p_http_manage->get_connection(fd);
                const char *respones_data = p_conn->get_respones();

                //发送数据
                int nLen = write(fd, respones_data, strlen(respones_data));

                //移除fd
                epoll_ctl(m_epoll_fd, EPOLL_CTL_DEL, fd, NULL);
                //断开连接
                close(fd);
                //销毁连接对象
                m_p_http_manage->remove_connection(fd);
            }
        }
    }
}

int server::create_socket(unsigned short port)
{

    unsigned value = 1;
    int listenFd = -1;

    struct sockaddr_in servAddr;
    memset(&servAddr, 0, sizeof(servAddr));

    servAddr.sin_family = AF_INET;
    servAddr.sin_addr.s_addr = htonl(INADDR_ANY);
    servAddr.sin_port = htons(port);

    //创建套接字
    if ((listenFd = socket(AF_INET, SOCK_STREAM, 0)) == -1)
    {
        printf("create socket error: %s(errno: %d)\n", strerror(errno), errno);
        return 0;
    }

    //设置可复用
    setsockopt(listenFd, SOL_SOCKET, SO_REUSEADDR, &value, sizeof(value));

    //绑定套接字
    if (bind(listenFd, (struct sockaddr *)&servAddr, sizeof(servAddr)))
    {
        printf("bind socket error: %s(errno: %d)\n", strerror(errno), errno);
        return 0;
    }

    //开始监听，设置最大连接请求
    if (listen(listenFd, 10) == -1)
    {
        printf("listen socket error: %s(errno: %d)\n", strerror(errno), errno);
        return 0;
    }

    return listenFd;
}

int server::set_socket_non_blocking(int fd)
{
    int flags = -1;
    int s = -1;

    flags = fcntl(fd, F_GETFL, 0);
    if (flags == -1)
    {
        perror("fcntl");
        return -1;
    }

    flags |= O_NONBLOCK;
    s = fcntl(fd, F_SETFL, flags);
    if (s == -1)
    {
        perror("fcntl");
        return -1;
    }
    return 0;
}

int server::create_epoll()
{
    m_epoll_fd = epoll_create(MAX_EVENTS);
    if (-1 == m_epoll_fd)
    {
        printf("epoll create failed\r\n");
        return -1;
    }

    return m_epoll_fd;
}
